package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.VirtualGoodsSupplierBo;
import com.fjwt.gz.core.third.interfaces.OutSideSupplierService;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.core.utils.jasypt.JasyptUtil;
import com.fjwt.gz.db.dto.AwardVirtualSupplierDTO;
import com.fjwt.gz.db.entity.AwardVirtualSupplierEntity;
import com.fjwt.gz.db.entity.SysConfig;
import com.fjwt.gz.db.vo.AwardVirtualSupplierVO;
import com.fjwt.gz.service.mapper.AwardVirtualSupplierMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  虚拟商品供应商表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardVirtualSupplierService extends ServiceImpl<AwardVirtualSupplierMapper, AwardVirtualSupplierEntity> {


    @Autowired
    private AwardVirtualOutsideService awardVirtualOutsideService;

    @Autowired
    private SysConfigService sysConfigService;

    private static final String PREFIX = "SUPPLIER_";
    private static final String SALT = "SUPPLIER_PASSWORD";

    /**
     * 获取供应商列表
     * @param iPage 分页
     * @param supplierDTO 查询条件
     * @return
     */
    public IPage<AwardVirtualSupplierVO> queryList(IPage iPage, AwardVirtualSupplierDTO supplierDTO) {
        IPage<AwardVirtualSupplierVO> result = baseMapper.selectSupplierList(iPage, supplierDTO);
        List<AwardVirtualSupplierVO> records = result.getRecords();
        // 查询配置表中的信息
        records.forEach(vo -> {
            SysConfig supplierConfig = sysConfigService.getById(PREFIX + vo.getVirtualSupplierId());
            if (supplierConfig != null) {
                JSONObject jsonObject = JSONObject.parseObject(supplierConfig.getConfigVal());
                vo.setUsername((String) jsonObject.get("username"));
                vo.setAuthConfig(DesensitizedUtil.mobilePhone((String) jsonObject.get("authConfig")));
                vo.setPassword(DesensitizedUtil.password(JasyptUtil.decrypt(SALT, (String) jsonObject.get("password"))));
            }
            vo.setChecked(vo.getState() == 1);
        });
        if (StrUtil.isNotBlank(supplierDTO.getUsername())) {
            records = result.getRecords().stream()
                    .filter(f -> f.getUsername().contains(supplierDTO.getUsername()))
                    .toList();
        }
        result.setRecords(records);
        return result;
    }

    /**
     * 添加供应商
     * @param supplierDTO
     * @param sysUserId
     */
    @Transactional(rollbackFor = Exception.class)
    public void addSupplier(AwardVirtualSupplierDTO supplierDTO, Long sysUserId) {
        if (StringUtils.isBlank(supplierDTO.getSupplierName()) || StringUtils.isBlank(supplierDTO.getAuthConfig())
                || StringUtils.isBlank(supplierDTO.getWebsiteUrl()) || supplierDTO.getState() == null
                || StringUtils.isBlank(supplierDTO.getUsername()) || StringUtils.isBlank(supplierDTO.getPassword())) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualSupplierEntity supplierEntity = BeanUtil.copyProperties(supplierDTO, AwardVirtualSupplierEntity.class);
        supplierEntity.setCreatedUid(sysUserId);
        save(supplierEntity);

        SysConfig sysConfig = buildSysConfig(supplierDTO, supplierEntity.getVirtualSupplierId());
        sysConfigService.save(sysConfig);
    }

    /**
     * 修改供应商
     * @param supplierDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSupplier(AwardVirtualSupplierDTO supplierDTO) {
        if (StringUtils.isBlank(supplierDTO.getSupplierName()) || StringUtils.isBlank(supplierDTO.getWebsiteUrl())
                || supplierDTO.getState() == null || StringUtils.isBlank(supplierDTO.getUsername()) || supplierDTO.getVirtualSupplierId() == null) {
            throw new BizException("请求参数不全，请检查！");
        }

        AwardVirtualSupplierEntity supplierEntity = this.getById(supplierDTO.getVirtualSupplierId());
        if (supplierEntity == null) {
            throw new BizException("该记录不存在！");
        }
        BeanUtil.copyProperties(supplierDTO, supplierEntity);
        updateById(supplierEntity);
        if (supplierDTO.getAuthConfig() != null || supplierDTO.getUsername() != null || supplierDTO.getPassword() != null) {
            SysConfig sysConfig = sysConfigService.getById(PREFIX + supplierDTO.getVirtualSupplierId());
            JSONObject jsonObject = JSONObject.parseObject(sysConfig.getConfigVal());
            if (supplierDTO.getAuthConfig() != null) {
                jsonObject.put("authConfig", supplierDTO.getAuthConfig());
            }
            if (supplierDTO.getUsername() != null) {
                jsonObject.put("username", supplierDTO.getUsername());
            }
            if (supplierDTO.getPassword() != null) {
                jsonObject.put("password", JasyptUtil.encrypt(SALT, supplierDTO.getPassword()));
            }
            sysConfig.setConfigVal(jsonObject.toJSONString());
            sysConfigService.updateById(sysConfig);
        }
    }

    /**
     * 修改供应商状态
     * @param supplierDTO
     */
    public void updateStateById(AwardVirtualSupplierDTO supplierDTO) {
        if (supplierDTO.getVirtualSupplierId() == null || supplierDTO.getState() == null ) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualSupplierEntity supplierEntity = getById(supplierDTO.getVirtualSupplierId());
        if (supplierEntity == null) {
            throw new BizException("该记录不存在！");
        }
        supplierEntity.setState(supplierDTO.getState());
        updateById(supplierEntity);
    }



    /**
     * 拉取供应商商品信息
     * @param supplierDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void getGoodsList(AwardVirtualSupplierDTO supplierDTO) {
        if (ObjectUtils.isEmpty(supplierDTO.getVirtualSupplierId())) {
            throw new BizException("请选择要拉取商品的供应商");
        }
        AwardVirtualSupplierEntity supplierEntity = baseMapper.selectById(supplierDTO.getVirtualSupplierId());
        if (ObjectUtils.isEmpty(supplierEntity) || 0 == supplierEntity.getState() || StrUtil.isBlank(supplierEntity.getSupplierName())) {
            throw new BizException("供应商状态异常，请检查");
        }

        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(supplierEntity.getSupplierName() + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        //获取供应商配置信息
        JSONObject supplierConfig = getSupplierConfig(supplierEntity.getVirtualSupplierId());
        if (supplierConfig == null || !supplierConfig.containsKey("authConfig")) {
            throw new BizException("该供应商配置信息异常，请检查");
        }
        Integer page = 1;
        Integer allPage;
        do {
            log.info("开始拉取供应商商品信息，供应商id：{}，页数{}", supplierDTO.getVirtualSupplierId(), page);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("page", page);
            jsonObject.put("limit", 50);
            VirtualGoodsSupplierBo supplierBo = BeanUtil.copyProperties(supplierEntity, VirtualGoodsSupplierBo.class);
            supplierBo.setAuthConfig((String) supplierConfig.get("authConfig"));
            JSONObject repJson = outSideSupplierService.getAllGoods(jsonObject, supplierBo);

            List<JSONObject> data = repJson.getObject("data", new TypeReference<List<JSONObject>>() {});
            awardVirtualOutsideService.saveList(data, supplierEntity.getVirtualSupplierId());

            allPage = repJson.getInteger("allpage");
            page ++;

            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }while (page <= allPage);
        log.info("拉取供应商的商品信息结束，供应商id：{}，总页数{}", supplierDTO.getVirtualSupplierId(), allPage);
    }

    /**
     * 设置供应商商品回调地址
     * @param supplierDTO
     */
    public void setGoodsNotifyUrl(AwardVirtualSupplierDTO supplierDTO) {
        if (ObjectUtils.isEmpty(supplierDTO.getVirtualSupplierId())) {
            throw new BizException("请选择要设置回调地址的供应商");
        }
        if (StrUtil.isBlank(supplierDTO.getNotifyUrl())) {
            throw new BizException("请选择要设置的回调地址");
        }
        AwardVirtualSupplierEntity supplierEntity = baseMapper.selectById(supplierDTO.getVirtualSupplierId());
        if (ObjectUtils.isEmpty(supplierEntity) || 0 == supplierEntity.getState() || StrUtil.isBlank(supplierEntity.getSupplierName())) {
            throw new BizException("供应商状态异常，请检查");
        }

        OutSideSupplierService outSideSupplierService = SpringBeansUtil.getBean(supplierEntity.getSupplierName() + "OutSideSupplierService", OutSideSupplierService.class);
        if (outSideSupplierService == null) {
            throw new BizException("该供应商暂不支持该功能");
        }
        //获取供应商配置信息
        JSONObject supplierConfig = getSupplierConfig(supplierEntity.getVirtualSupplierId());
        if (supplierConfig == null || !supplierConfig.containsKey("authConfig")) {
            throw new BizException("该供应商配置信息异常，请检查");
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("notifyUrl", supplierDTO.getNotifyUrl());
        VirtualGoodsSupplierBo supplierBo = BeanUtil.copyProperties(supplierEntity, VirtualGoodsSupplierBo.class);
        supplierBo.setAuthConfig((String) supplierConfig.get("authConfig"));
        outSideSupplierService.setGoodsNotifyUrl(jsonObject, supplierBo);
    }

    /**
     * 获取供应商的配置信息
     * @param virtualSupplierId 供应商id
     * @return 配置信息
     */
    public JSONObject getSupplierConfig(Long virtualSupplierId) {
        SysConfig sysConfig = sysConfigService.getById(PREFIX + virtualSupplierId);
        return JSONObject.parseObject(sysConfig.getConfigVal());
    }

    private SysConfig buildSysConfig(AwardVirtualSupplierDTO supplierDTO, Long supplierId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("authConfig", supplierDTO.getAuthConfig());
        jsonObject.put("username", supplierDTO.getUsername());
        jsonObject.put("password", JasyptUtil.encrypt(SALT, supplierDTO.getPassword()));

        return new SysConfig()
                .setConfigKey(PREFIX + supplierId)
                .setConfigName("供应商管理参数配置")
                .setConfigDesc("供应商通信认证参数及用户名和密码配置")
                .setGroupKey("supplierConfig")
                .setGroupName("供应商参数配置")
                .setConfigVal(jsonObject.toJSONString())
                .setType("text");
    }
}
